import React, {PureComponent, Fragment} from 'react';
import {routerRedux, Link} from 'dva/router';
import {connect} from 'dva';
import moment from 'moment';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Icon,
    Button,
    Dropdown,
    Menu,
    InputNumber,
    DatePicker,
    Modal,
    message,
    Badge,
    Divider,
    Checkbox,
    Popconfirm,
} from 'antd';
import StandardTable from 'components/GoodsTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Authorized from '../../utils/Authorized';
import {getAuthority} from '../../utils/authority';
import {HOST} from '../../utils/setting';
import G from '../../utils/g';

import styles from './GoodsList.less';

const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj =>
    Object.keys(obj)
        .map(key => obj[key])
        .join(',');
const statusMap = ['default', 'success', 'error', 'warning'];
const status = ['仓库', '出售中', '售罄', '待审核'];

const CreateForm = Form.create()(props => {
    const {modalVisible, form, handleAdd, handleModalVisible} = props;
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            form.resetFields();
            handleAdd(fieldsValue);
        });
    };
    return (
        <Modal
            title="新建规则"
            visible={modalVisible}
            onOk={okHandle}
            onCancel={() => handleModalVisible()}
        >
            <FormItem labelCol={{span: 5}} wrapperCol={{span: 15}} label="描述">
                {form.getFieldDecorator('desc', {
                    rules: [{required: true, message: 'Please input some description...'}],
                })(<Input placeholder="请输入"/>)}
            </FormItem>
        </Modal>
    );
});

@connect(({goodsList, loading}) => ({
    goodsList,
    loading: loading.models.goodsList,
}))
@Form.create()
export default class TableList extends PureComponent {
    state = {
        modalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        addInputValue: '',
        checkedGroupList: [],
    };

    componentDidMount() {
        // this.onGroupInfo = {
        //   userIds : [],
        //   groupIds : []
        // };
        const {dispatch} = this.props;
        dispatch({
            type: 'goodsList/fetch',
        });
        dispatch({
            type: 'goodsList/getCategory',
        });
        dispatch({
            type: 'goodsList/getGroup',
        });
        if (getAuthority() == 'admin') { //管理员需要获取商家列表
            dispatch({
                type: 'goodsList/getShopList',
            });
        }

    }

    handleStandardTableChange = (pagination, filtersArg, sorter) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            startIndex: (pagination.current - 1) * pagination.pageSize,
            pageSize: pagination.pageSize,
            ...formValues,
            ...filters,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'goodsList/fetch',
            payload: params,
        });
    };

    handleFormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
        this.setState({
            formValues: {},
        });
        dispatch({
            type: 'goodsList/fetch',
            payload: {},
        });
    };

    toggleForm = () => {
        this.setState({
            expandForm: !this.state.expandForm,
        });
    };

    handleMenuClick = e => {
        const {dispatch} = this.props;
        const {selectedRows} = this.state;

        if (!selectedRows) return;

        switch (e.key) {
            case 'remove':
                dispatch({
                    type: 'goodsList/remove',
                    payload: {
                        no: selectedRows.map(row => row.no).join(','),
                    },
                    callback: () => {
                        this.setState({
                            selectedRows: [],
                        });
                    },
                });
                break;
            default:
                break;
        }
    };

    handleSelectRows = rows => {
        console.log('rows', rows);
        this.setState({
            selectedRows: rows,
        });
    };

    handleSearch = e => {
        e.preventDefault();

        const {dispatch, form} = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;

            const values = {
                ...fieldsValue,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };

            this.setState({
                formValues: values,
            });

            dispatch({
                type: 'goodsList/fetch',
                payload: values,
            });
        });
    };

    handleModalVisible = flag => {
        this.setState({
            modalVisible: !!flag,
        });
    };
    handleSelectGroup = row=> {
        console.log('row', [row]);
        let groups = [];  //计算出当前已有分组ID值
        this.props.goodsList.group.forEach(v=> {
            row.groups.forEach(s=> {
                if (v.name == s) {
                    groups.push(v.name);
                }
            })
        });

        this.setState({
            modalVisible: true,
            selectedRows: [row],
            checkedGroupList: groups,
        });
    };

    // handleAdd = fields => {
    //   this.props.dispatch({
    //     type: 'goodsList/add',
    //     payload: {
    //       description: fields.desc,
    //     },
    //   });
    //
    //   message.success('添加成功');
    //   this.setState({
    //     modalVisible: false,
    //   });
    // };

    handleAddInput = (e) => {
        this.setState({
            addInputValue: e.target.value,
        });
    }

    onGroupChange = (checkedValues)=> {
        console.log(checkedValues);
        this.setState({
            checkedGroupList: checkedValues
        });
        //this.onGroupInfo.groupIds = checkedValues;
    }

    handleAddGroup = (e)=> {
        e.preventDefault();
        const {addInputValue} = this.state;
        const {dispatch}  = this.props;
        if (addInputValue == '') {
            return false;
        }
        dispatch({
            type: 'goodsList/addGroup',
            payload: {
                name: addInputValue
            },
        }).then(()=> {
            this.setState({
                addInputValue: ''
            });
        })
    };

    handleGroup = ()=> {
        //const {userIds} = this.onGroupInfo;
        const {selectedRows, checkedGroupList} = this.state;
        if (checkedGroupList.length == 0) {
            //console.error('选中的分组用户为空');
            message.error('你还未选择分组');
            return;
        }
        //console.log(this.onGroupInfo);
        this.props.dispatch({
            type: 'goodsList/goodsGroup',
            payload: {
                ids: selectedRows.map(row => row.id).join(','),
                groups: checkedGroupList.join(',')
            }
        }).then(()=> {
            //message.success('分组成功');
            this.setState({
                modalVisible: false,
                checkedGroupList: [],
            });
        });

    };

    renderSimpleForm() {
        const {getFieldDecorator} = this.props.form;
        const {category, group, shopList} = this.props.goodsList;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem label="商品名称">
                            {getFieldDecorator('name')(<Input placeholder="请输入"/>)}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="状态">
                            {getFieldDecorator('status')(
                                <Select placeholder="请选择" style={{width: '100%'}}>
                                    <Option value="0">仓库</Option>
                                    <Option value="3">待审核</Option>
                                    <Option value="1">出售中</Option>
                                    <Option value="2">售罄</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="分类">
                            {getFieldDecorator('categoryId')(
                                <Select placeholder="请选择" style={{width: '100%'}}>
                                    {
                                        category.map(v=> {
                                            return <Option value={v.id} key={v.id}>{v.name}</Option>
                                        })
                                    }
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                </Row>
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem label="商品分组">
                            {getFieldDecorator('groups')(
                                <Select placeholder="请选择" style={{width: '100%'}}>
                                    {
                                        group.map(v=> {
                                            return <Option value={v.name} key={v.id}>{v.name}</Option>
                                        })
                                    }
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Authorized authority="admin">
                        <Col md={8} sm={24}>
                            <FormItem label="商家列表">
                                {getFieldDecorator('business_id')(
                                    <Select placeholder="请选择" style={{width: '100%'}}>
                                        {
                                            shopList.map(v=> {
                                                return <Option value={v.userId}
                                                               key={'business' + v.userId}>{v.userInfo.nickname}</Option>
                                            })
                                        }
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Authorized>
                    <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    handleChangeStatus = (status, id)=> {
        const {selectedRows} = this.state;
        const ids = id ? [id] : selectedRows.map(v=> {
            return v.id
        });
        this.props.dispatch({
            type: 'goodsList/changeStatus',
            payload: {
                ids: ids.join(','),
                status: status
            }
        }).then(res=> {
            //console.log(res);
            this.setState({
                selectedRows: []
            });
        });
    };

    handleGoodsCopy = (id)=> {
        this.props.dispatch({
            type: 'goodsList/copy',
            payload: {id}
        });
    }

  handleSaveItem = (record) =>{
    this.props.dispatch({
      type: 'goodsList/save',
      payload: {
        bindArticleGoods : record
      }
    });
  }

    openDetail = (id)=>{
        G.openH5(`${HOST}/shop/h5/#/detail?id=${id}`);
    }

    render() {
        const {goodsList: {data, group}, loading} = this.props;
        const {selectedRows, modalVisible, addInputValue, checkedGroupList} = this.state;
        const _this = this;
        const columns = [
            {
                title: '图片',
                dataIndex: 'imgs',
                render(val) {
                    return <img src={`${val[0]}?imageView2/1/w/50`} width={50}/>;
                },
            },
            {
                title: '名称',
                dataIndex: 'name',
                render(val, record){
                    return <a onClick={()=>{_this.openDetail(record.id)}}>{record.name}</a>
                }
            },
            {
                title: '价格',
                dataIndex: 'min_price',
                align: 'right',
                width: '100px',
                render: val => `${val || 0}元`,
            },
            {
                title: '访客数',
                dataIndex: 'uv',
                align: 'right',
                width: '80px',
                render: val => `${val || 0}`,
            },
            {
                title: '浏览量',
                dataIndex: 'pv',
                align: 'right',
                width: '80px',
                render: val => `${val || 0}`,
            },
            {
                title: '库存',
                dataIndex: 'stock_count',
                align: 'right',
                width: '60px',
                render: val => `${val || 0}`,
            },
            {
                title: '总销量',
                dataIndex: 'total_sales',
                align: 'right',
                width: '80px',
                sorter: true,
                render: val => `${val || 0}`,
            },
            {
                title: '商家',
                dataIndex: 'goods_nickname'
            },
            {
                title: '状态',
                dataIndex: 'status',
                filters: [
                    {
                        text: status[0],
                        value: 0,
                    },
                    {
                        text: status[1],
                        value: 1,
                    },
                ],
                render(val) {
                    return <Badge status={statusMap[val]} text={status[val]}/>;
                },
            },
            {
                title: '更新时间',
                dataIndex: 'updateTime',
                sorter: true,
                render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
            },
            {
                title: '操作',
                render: (text, record) => (
                    <Fragment>
                        <Link to={`/goods/bind-article?id=${record.id}`} onClick={()=> {
                          this.handleSaveItem(record)
                        }}>文章管理</Link>
                        <Divider type="vertical"/>
                        <a onClick={()=> {
                            this.handleGoodsCopy(record.id)
                        }}>复制</a>
                        <Divider type="vertical"/>
                        <a onClick={()=> {
                            this.handleSelectGroup(record)
                        }}>分组</a>
                        <Divider type="vertical"/>
                        <Link to={`/goods/goods-add?id=${record.id}`}>编辑</Link>
                        {
                            record.status == 3 || record.status == 0 ?
                                <Authorized authority="admin">
                                    <Divider type="vertical"/>
                                    <a onClick={()=> {
                                        this.handleChangeStatus(1, record.id)
                                    }}>上架出售</a>
                                </Authorized> : null
                        }
                        {
                            record.status == 0 ?
                                <Authorized authority="business">
                                    <Divider type="vertical"/>
                                    <a onClick={()=> {
                                        this.handleChangeStatus(3, record.id)
                                    }}>提交审核</a>
                                </Authorized> : null
                        }
                        {
                            record.status == 1 ?
                                <Authorized authority="admin">
                                    <Divider type="vertical"/>
                                    <a onClick={()=> {
                                        this.handleChangeStatus(0, record.id)
                                    }}>下架</a>
                                </Authorized> : null
                        }
                    </Fragment>
                ),
            },
        ];

        //console.log('group', group);

        return (
            <div>
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
                        <div className={styles.tableListOperator}>
                            <Link to={`/goods/goods-add`}>
                                <Button icon="plus" type="primary">
                                    新建
                                </Button>
                            </Link>
                            {selectedRows.length > 0 && (
                                <span>
                  <Button onClick={this.handleModalVisible}>分组</Button>
                  <Popconfirm title="你确定要批量删除选中商品？" okText="确定" cancelText="取消" onConfirm={()=> {
                      this.handleChangeStatus(-1)
                  }}>
                    <Button>删除</Button>
                  </Popconfirm>
                  <Button onClick={()=> {
                      this.handleChangeStatus(0)
                  }}>放入仓库</Button>
                  <Authorized authority="admin">
                    <Button onClick={()=> {
                        this.handleChangeStatus(1)
                    }}>上架出售</Button>
                  </Authorized>
                </span>
                            )}
                        </div>
                        <StandardTable
                            selectedRows={selectedRows}
                            loading={loading}
                            data={data}
                            columns={columns}
                            onSelectRow={this.handleSelectRows}
                            onChange={this.handleStandardTableChange}
                        />
                    </div>
                </Card>
                <Modal
                    title="选择分组"
                    visible={modalVisible}
                    onOk={this.handleGroup}
                    onCancel={() => this.handleModalVisible()}
                >
                    <Form layout="inline" onSubmit={this.handleAddGroup}>
                        <FormItem
                            label="分组名"
                        >
                            <Input placeholder="输入新的分组名" onChange={this.handleAddInput} value={addInputValue}
                                   style={{width: 300}}/>
                        </FormItem>
                        <FormItem>
                            <Button
                                type="default"
                                htmlType="submit"
                            >
                                新增
                            </Button>
                        </FormItem>
                    </Form>
                    <div style={{'marginTop': '24px'}}>
                        <Checkbox.Group style={{width: '100%'}} value={checkedGroupList} onChange={this.onGroupChange}>
                            <Row >
                                {
                                    group.map(v=> {
                                        return <Col span={8} key={v.id}><Checkbox
                                            value={v.name}>{v.name}</Checkbox></Col>
                                    })
                                }
                            </Row>
                        </Checkbox.Group>
                    </div>
                </Modal>
            </div>
        );
    }
}
